package org.xinjiang.data.migration.common.lambda;

import org.apache.commons.collections4.CollectionUtils;

import java.util.Collection;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * IF帮助类
 *
 * @author wenjie
 * @date 2022/11/25
 */
public final class If<T> {

    private boolean value;

    private If(Boolean value) {
        this.value = value;
    }

    public static <T> If<T> of(boolean value) {
        return new If(value);
    }

    public static <T> If<T> ofNull(Object value) {
        return new If(value == null);
    }

    public static <T> If<T> ofEmpty(Collection value) {
        return new If(CollectionUtils.isEmpty(value));
    }

    public static <T> If<T> ofNotEmpty(Collection value) {
        return new If(CollectionUtils.isNotEmpty(value));
    }

    public static <T> If<T> ofEqual(Object o1, Object o2) {
        return new If(o1 != null && o1.equals(o2));
    }

    public void isTrue(Action action) {
        if (value) {
            action.doIt();
        }
    }

    public void is(Action s, Action f) {
        if (value) {
            s.doIt();
        } else {
            f.doIt();
        }
    }

    public <R> R isTrue(T t, Function<T, R> func) {
        if (value) {
            return func.apply(t);
        }
        return null;
    }

    public void isNotTrue(Action action) {
        if (!value) {
            action.doIt();
        }
    }

    public <R> R isNotTrue(T t, Function<T, R> func) {
        if (!value) {
            return func.apply(t);
        }
        return null;
    }

    public <X extends Throwable> T isTrueThrow(Supplier<? extends X> supplier) throws X {
        if (value) {
            throw supplier.get();
        }
        return null;
    }

    public <X extends Throwable> T isNotTrueThrow(Supplier<? extends X> supplier) throws X {
        if (!value) {
            throw supplier.get();
        }
        return null;
    }

}
